package com.example.zbh.dsliao.ui.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.easemob.EMCallBack;
import com.easemob.EMNotifierEvent;
import com.easemob.EMValueCallBack;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.example.zbh.dsliao.R;
import com.example.zbh.dsliao.db.DatabaseHelper;
import com.example.zbh.dsliao.presenter.BasePresenter;
import com.example.zbh.dsliao.ui.activty.BackGroundActivity;
import com.example.zbh.dsliao.ui.activty.BlackActivity;
import com.example.zbh.dsliao.ui.activty.LoginActivity;
import com.example.zbh.dsliao.ui.activty.MainActivity;
import com.example.zbh.dsliao.ui.activty.SetPersonnalActivity;
import com.example.zbh.dsliao.ui.activty.TwoCodeActivity;
import com.example.zbh.dsliao.ui.activty.TypeFaceActivity;
import com.example.zbh.dsliao.utils.DliaoUtils;
import com.example.zbh.dsliao.utils.PreferenceHelper;
import com.example.zbh.dsliao.view.CustomChangeDialog;
import com.example.zbh.dsliao.view.CustomDialog;



import de.greenrobot.event.EventBus;


/**
 * 设置界面
 */
public class SettingFragment extends MVPBaseFragment implements View.OnClickListener {



    private RelativeLayout blackLayout, editLayout, saoYsao, changeTypeFace, changeBackGround, deletePrefrenceLayout;

    private Button outLoginBtn;
    private CustomDialog customDialog;
    private TextView userNameTv;
    private ImageView isChangeImg, userImg;
    private PreferenceHelper preferenceHelper;
    private boolean isChange;



    @Override
    protected BasePresenter createPresenter() {
        return new BasePresenter();
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    /**
     * 监听主界面的eventbus发过来的的状态
     * (包括 1 == 账号被服务器删除
     * 2 == 账号被别的设备登录)
     * **/
    public void onEventMainThread(Integer data){
        if (data == 102){
            DliaoUtils.showDialogConnection(getActivity());
        }else if (data == 101){
            DliaoUtils.showDialogUserRemoved(getActivity());
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_set, container, false);
        preferenceHelper = PreferenceHelper.getInstance();
        blackLayout = (RelativeLayout) v.findViewById(R.id.blackLayout);//黑名单
        editLayout = (RelativeLayout) v.findViewById(R.id.editLayout);//个人资料
        outLoginBtn = (Button) v.findViewById(R.id.outLoginBtn);//退出按钮
        userNameTv = (TextView) v.findViewById(R.id.userNameTv);
        isChangeImg = (ImageView) v.findViewById(R.id.isChangeImg);//新消息按钮
        saoYsao = (RelativeLayout) v.findViewById(R.id.saoYsao);
        userImg = (ImageView) v.findViewById(R.id.userImg);//头像
        changeTypeFace = (RelativeLayout) v.findViewById(R.id.changeTypeFace);
        changeBackGround = (RelativeLayout) v.findViewById(R.id.changeBackGround);
        deletePrefrenceLayout = (RelativeLayout) v.findViewById(R.id.deletePrefrenceLayout);//清空缓存
        saoYsao.setOnClickListener(this);
        //获得当前设置的状态
        isChange = preferenceHelper.getNewNotify();
        if(isChange == true){
            isChangeImg.setImageResource(R.mipmap.dl_open_icon);
        }else if(isChange == false){
            isChangeImg.setImageResource(R.mipmap.dl_close_icon);
        }
        //parse的用户名
        String nickname = preferenceHelper.getThreeCurrentUserNick();
        //环信服务器的用户名
        String username = EMChatManager.getInstance().getCurrentUser();

        if (nickname != null){
            userNameTv.setText(nickname);
        }

        String avater = preferenceHelper.getThreeCurrentUserAvatar();
        setUserAvatar(getActivity() ,avater, userImg);

        return v;
    }




    private void setUserAvatar(Context context, String avater, ImageView userImg) {
        if (avater != null){
            Glide.with(context).load(avater).into(userImg);
            Log.d("wonima", "wonima" + ">>>>>");
        }
    }



    @Override
    protected void initData() {
        blackLayout.setOnClickListener(this);
        outLoginBtn.setOnClickListener(this);
        editLayout.setOnClickListener(this);
        customDialog = new CustomDialog(getActivity(), "正在退出...");
        isChangeImg.setOnClickListener(this);
        changeTypeFace.setOnClickListener(this);
        changeBackGround.setOnClickListener(this);
        deletePrefrenceLayout.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.blackLayout://黑名单
                Intent intent = new Intent(getActivity(), BlackActivity.class);
                startActivity(intent);
                break;
            case R.id.outLoginBtn:
                loginout();//退出登录
                break;
            case R.id.editLayout://编辑个人资料
                Intent intent1 = new Intent(getActivity(), SetPersonnalActivity.class);
                //将正在线的用户名传到个人资料页面
                intent1.putExtra("username", EMChatManager.getInstance().getCurrentUser());
                startActivity(intent1);
                break;
            case R.id.isChangeImg://新消息提示
                isChange();
                break;
            case R.id.saoYsao://扫一扫
                Intent intentS = new Intent();
                break;
            case R.id.changeTypeFace:
                Intent intentC = new Intent();
                intentC.setClass(getActivity(), TypeFaceActivity.class);
                getActivity().startActivity(intentC);
                break;
            case R.id.changeBackGround:
                Intent intentB = new Intent();
                intentB.setClass(getActivity(), BackGroundActivity.class);
                getActivity().startActivity(intentB);
                break;
            case R.id.create_two_code:
                Intent intentCode = new Intent();
                intentCode.setClass(getActivity(), TwoCodeActivity.class);
                getActivity().startActivity(intentCode);
            case R.id.deletePrefrenceLayout://清空缓存
                clickdeletePrefrenceLayout();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK){
            if (data != null){
                String result = data.getStringExtra("resultData");
                Toast.makeText(getActivity(),result,Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 清空缓存
     * **/
    private void clickdeletePrefrenceLayout() {
        final CustomChangeDialog customChangeDialog = new CustomChangeDialog(getActivity(), "您确定要清空缓存么?", View.GONE, "", "确定", "取消");
        customChangeDialog.show();
        customChangeDialog.setCustomChangeDialogListener(new CustomChangeDialog.CustomChangeDialogListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.changeTwoBtn:
                        customChangeDialog.dismiss();
                        //清空图片viewpager内容
                        DatabaseHelper.getInstance().deleteImageViewPager();
                        Toast.makeText(getActivity(), "清除成功", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.cancleBtn:
                        customChangeDialog.dismiss();
                        break;
                }
            }
        });
    }


    /**
     * 是否有新消息提示
     * **/
    private void isChange() {
        boolean ischange = preferenceHelper.getNewNotify();
        if (ischange == true){
            //点击设置false
            preferenceHelper.setNewNotify(false);
            //切换图片
            isChangeImg.setImageResource(R.mipmap.dl_close_icon);
        }else if (ischange == false){
            preferenceHelper.setNewNotify(true);
            isChangeImg.setImageResource(R.mipmap.dl_open_icon);
        }
    }

    /**
     * 退出登录
     * **/
    private void loginout() {
        //弹出提示dialog
        final CustomChangeDialog customChangeDialog = new CustomChangeDialog(getActivity(), "确定要退出么???", View.GONE, "", "确定!", "取消");
        customChangeDialog.show();
        customChangeDialog.setCustomChangeDialogListener(new CustomChangeDialog.CustomChangeDialogListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.changeTwoBtn://点击确定按钮
                        customChangeDialog.dismiss();//关闭选择dialog
                        PreferenceHelper.getInstance().removeCurrentUserName();
                        PreferenceHelper.getInstance().removeCurrentUserPsw();
                        isChangeDialog();
                        break;
                    case R.id.cancleBtn://取消按钮
                        customChangeDialog.dismiss();
                        break;

                }
            }
        });

    }

    /**
     * 点击确定退出
     * **/
    private void isChangeDialog() {
        customDialog.show();//显示等待dialog
        EMChatManager.getInstance().logout(new EMCallBack() {
            @Override
            public void onSuccess() {
                customDialog.dismiss();
                //开启一个新线程(更新dialog的)
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //退出登录成功后回到登录页面
                        ((MainActivity) getActivity()).finish();
                        startActivity(new Intent(getActivity(), LoginActivity.class));
                    }
                });
            }

            @Override
            public void onError(int i, String s) {
            }

            @Override
            public void onProgress(int i, String s) {
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();

        refresh();

    }

    /**
     * 刷新
     * **/
    private void refresh() {
        //parse的用户名
        String nickname = preferenceHelper.getThreeCurrentUserNick();
        //环信服务器的用户名
        String username = EMChatManager.getInstance().getCurrentUser();

        if (nickname != null){
            userNameTv.setText(nickname);
        }

        String avater = preferenceHelper.getThreeCurrentUserAvatar();
        setUserAvatar(getActivity() ,avater, userImg);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
